package org.leon.framework;

import org.leon.HttpServlet;
import org.leon.Request;
import org.leon.Response;
import org.leon.util.HttpProtocolUtil;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {


    private Socket socket;
    private Map<String, HttpServlet> servletMap;

    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            try {
                Request request = new Request(inputStream);
                Response response = new Response(socket.getOutputStream());


                String requestUrl = request.getUrl();
                String host = request.getHost();

                if (requestUrl.contains("favicon.ico")){
                    response.outputString(HttpProtocolUtil.httpHeader404());
                    return;
                }

                requestUrl = requestUrl.substring(1);

                String contextName = requestUrl.substring(0, requestUrl.indexOf("/"));
                String requestPath = requestUrl.substring(requestUrl.indexOf("/"));


                MappedHost mappedHost = mapper.getMappedHost(host);
                if (mappedHost != null) {
                    Context hostContext = mappedHost.getContext(contextName);
                    if (hostContext != null) {
                        Wrapper wrapper = hostContext.getWrapper(requestPath);
                        if (wrapper != null) {
                            if ("GET".equals(request.getMethod().toUpperCase())) {
                                wrapper.getInstance().doGet(request, response);
                            } else {
                                wrapper.getInstance().doPost(request, response);
                            }

                            return;
                        }
                    }
                }

                // 如果上面路径找不到，输出 404
                response.outputHtml(requestUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
